<template>
	<div v-show="showflag" class="container flex-column flex-space-between font-16px">
		<view class="one flex-column flex-center ">
			<view class="item border-bottom flex-row align-items-center ">
				<text class="text">设备型号：</text>
				<!-- <input type="text" class="input-content" v-model="submitInfo.equipmentTypeNumber" placeholder="请输入设备型号"/> -->
				<!-- 下面注释代码是选择添加数据以后客户有需求再改 -->
				<text v-show="false===flags.typeNumberFlag" class="picker" @tap="handleTap('picker1')">请选择设备型号</text>
				<text v-show="true===flags.typeNumberFlag" class="select" @tap="handleTap('picker1')">{{submitInfo.equipmentTypeNumber}}</text>
				<lb-picker ref="picker1" mode="multiSelector" :list="equipmentTypeNumbers" :level="3" confirm-color="#09BB07"
				 @change="handleChange" @confirm="handleConfirm" @cancel="handleCancel">
				</lb-picker>
			</view>
		
			<view class="item border-bottom flex-row align-items-center "><text class="text">设备机身号：</text>
				<input class="input-content" v-model="submitInfo.fuselageNumber" placeholder="请输入设备机身号" /></view>


			<view class="item border-bottom flex-row align-items-center "><text class="text">墨水型号：</text>
				<input class="input-content" v-model="submitInfo.solventType" placeholder="请输入墨水型号" /></view>
			<view class="item border-bottom flex-row align-items-center "><text class="text">溶剂型号：</text>
				<input class="input-content" v-model="submitInfo.inkTankTypeNumber" placeholder="请输入溶剂型号" /></view>

			<!-- <text v-show="false===flags.solventTypeFlag" class="picker" @tap="handleTap('picker3')">请选择墨水溶剂型号</text>
				<text v-show="true===flags.solventTypeFlag" class="select font-13px" @tap="handleTap('picker3')">{{submitInfo.inkTankTypeNumber}}</text>
				<lb-picker 
					ref="picker3" 
					mode="multiSelector" 
					:list="inkTankTypeNumbers"
					 :level="2" 
					 confirm-color="#09BB07" 
					 @change="handleChange3" 
					 @confirm="handleConfirm3" 
					 @cancel="handleCancel3">
				</lb-picker> -->
			<view class="textarea flex-row ">
				<text class="text">设备配置：</text>
				<textarea  class="input-content" v-model="submitInfo.configuration" placeholder="请输入设备配置" />
				<!-- <text v-show="false===flags.configFlag" class="picker" @tap="handleTap('picker2')">请选择设备配置</text>
				<text v-show="true===flags.configFlag" class="select" @tap="handleTap('picker2')">{{submitInfo.configuration}}</text>
				<lb-picker 
					ref="picker2" 
					mode="multiSelector" 
					:list="configurations" 
					:level="2"
					 confirm-color="#09BB07" 
					 @change="handleChange2" 
					 @confirm="handleConfirm2"
					 @cancel="handleCancel2">
				</lb-picker> -->
			</view>
		</view>
		</view>
<!-- 		<view class="one1 flex-column flex-center">
			<view class="textarea flex-row ">
				<text class="text">设备配置：</text>
				<textarea  class="input-content" v-model="submitInfo.configuration" placeholder="请输入设备配置" />
			</view>
		</view> -->
		
		<view class="two flex-column flex-center">
			<view class="item border-bottom flex-row align-items-center "><text class="text">安装日期：</text>
				<text v-show="false===flags.dateFlag" class="picker" @tap="handleTap('picker4')">请选择安装日期</text>
				<text v-show="true===flags.dateFlag" class="select" @tap="handleTap('picker4')">{{submitInfo.installDate}}</text>
				<w-picker themeColor="#09BB07" mode="date" startYear="2017" endYear="2029" value="2020-03-07" :current="true"
				 fields="day" @confirm="dateOnConfirm($event,'date')" @cancel="onCancel" :disabled-after="true" ref="picker4">
				</w-picker>
			</view>
			<view class="item border-bottom flex-row align-items-center"><text class="text">设备维护专员：</text>
				<text v-show="false===flags.principalFlag" class="picker" @tap="handleTap('picker5')">请选择维护专员</text>
				<text v-show="true===flags.principalFlag" class="select" @tap="handleTap('picker5')">{{submitInfo.maintainPeople}}</text>
				<lb-picker ref="picker5" mode="multiSelector" :list="maintainPeoples" :level="1" confirm-color="#09BB07" @change="handleChange4"
				 @confirm="handleConfirm4" @cancel="handleCancel4">
				</lb-picker>
			</view>
		</view>
		<view class="three flex-column flex-center">
			<view class="item border-bottom flex-row align-items-center "><text class="text">客户公司：</text><input class="input-content"
				 v-model="submitInfo.subordinateCompany" placeholder="请输入客户公司名称" /></view>
			<view class="item border-bottom flex-row align-items-center"><text class="text">客户地址：</text><input class="input-content"
				 v-model="submitInfo.customerDetailedAddress" placeholder="请输入客户详细地址" /></view>
			<view class="item border-bottom flex-row align-items-center"><text class="text">客户联系人：</text><input class="input-content"
				 v-model="submitInfo.customer" placeholder="请输入客户联系人" /></view>
			<view class="item border-bottom flex-row align-items-center"><text class="text">客户联系方式：</text><input class="input-content"
				 v-model="submitInfo.customerContact" placeholder="请输入客户联系方式" /></view>
		</view>
		<view class="four flex-column  flex-center">
			<text class="item border-bottom text">上传图片</text>
			<view class="add-img-box">
				<sunui-upbasic class="upload" :upImgConfig="upImgBasic" @onUpImg="upBasicData" @onImgDel="delImgInfo" ref="uImage"></sunui-upbasic>
			</view>
		</view>
		<button type="primary" class="submit-button" @click="on">确定</button>
	</div>
</template>

<script>
	import validate from '@/common/js_sdk/fshjie-formvalidate/ys-validate.js'
	import sunuiUpbasic from '@/components/sunui-upimg/sunui-upbasic.vue'
	import LbPicker from '@/components/lb-picker/index.vue'
	import wPicker from "@/components/w-picker/w-picker.vue"
	import config from '@/config/index.js'
	import {
		creteEquipment,
		getEngineerList,
		getEquipmentTypeList
	} from '@/api/user/index.js'
	export default {
		components: {
			LbPicker,
			wPicker,
			sunuiUpbasic,
		},
		data() {
			return {
				// 是否提交成功
				isSuccess: false,
				showflag: false,
				//后台返回的图片地址
				basicArr: [],
				// 基础版配置
				upImgBasic: {
					// 后端图片接口地址
					basicConfig: {
						url: config.baseUrl + '/equipment?action=UploadFile'
					},
					// 是否开启提示(提醒上传图片的数量)
					// tips: false,
					// 是否开启notli(开启的话就是选择完直接上传，关闭的话当count满足数量时才上传)
					notli: true,
					// 图片数量
					count: 1,
					// 相机来源(相机->camera,相册->album,两者都有->all,默认all)
					sourceType: 'all',
					// 是否压缩上传照片(仅小程序生效)
					sizeType: true,
					// 上传图片背景修改 
					upBgColor: '#ededed',
					// 上传icon图标颜色修改(仅限于iconfont)
					upIconColor: '#666666',
					// 上传svg图标名称
					// upSvgIconName: 'icon-card',
					// 上传文字描述(仅限四个字)
					upTextDesc: '上传图片',
					// 删除按钮位置(left,right,bleft,bright),默认右上角
					delBtnLocation: '',
					// 是否隐藏添加图片
					// isAddImage: false,
					// 是否隐藏删除图标
					// isDelIcon: false,
					// 删除图标定义背景颜色
					// delIconColor: '',
					// 删除图标字体颜色
					// delIconText: '',
					// 上传图标替换(+),是个http,https图片地址(https://www.playsort.cn/right.png)
					iconReplace: '',
				},
				flags: {
					typeNumberFlag: false,
					configFlag: false,
					solventTypeFlag: false,
					dateFlag: false,
					principalFlag: false
				},
				equipmentTypeNumbers: [],
				// equipmentTypeNumbers: [{
				// 	 value: '1',
				// 	 label: '小花',
				// 	 }],
				configurations: [{
					label: '常规配置',
					value: '1',
					children: [{
						label: '自动Ai',
						value: '11'
					}]
				}],
				inkTankTypeNumbers: [{
					label: '日立',
					value: '1',
					children: [{
						label: '201-0001-085 抗迁移白色溶剂',
						value: '11'
					}]
				}],
				maintainPeoples: [{
					value: '1',
					label: '小花'
				}, {
					value: '2',
					label: '殷跃龙'
				}, {
					value: '3',
					label: '耀龙啊'
				}, {
					value: '4',
					label: '小花'
				}, {
					value: '5',
					label: '小花'
				}, {
					value: '6',
					label: '小花'
				}],
				submitInfo: {
					equipment_id: 3337,
					equipmentTypeNumber: '', //设备型号
					configuration: '', //设备配置
					fuselageNumber: '', //设备机身号
					inkTankTypeNumber: '', //墨水溶剂型号
					installDate: '', //安装日期
					maintainPeople: '', //负责人姓名
					maintainPeopleId: '', //负责人姓名
					subordinateCompany: '', //客户公司
					customerDetailedAddress: '', //客户公司地址
					customer: '', //客户联系人
					customerContact: '', //客户联系方式
					solventType:'',
					imgUrl: ""
				},
			};
		},
		methods: {

			//################################################获取当前位置############################################################
			getAuthorizeInfo(a = "scope.userLocation") { //1. uniapp弹窗弹出获取授权（地理，个人微信信息等授权信息）弹窗
				var _this = this;
				uni.authorize({
					scope: a,
					success() { //1.1 允许授权
						_this.getLocationInfo();
					},
					fail() { //1.2 拒绝授权
						console.log("你拒绝了授权，无法获得周边信息")
					}
				})
			},
			getLocationInfo() { //2. 获取地理位置
				var _this = this;
				uni.getLocation({
					type: 'wgs84',
					success(res) {
						console.log("你当前经纬度是：")
						console.log(res)
						let latitude, longitude;
						latitude = res.latitude.toString();
						longitude = res.longitude.toString();
						uni.request({
							header: {
								"Content-Type": "application/text"
							},
							url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude +
								'&key=TUMBZ-UQA62-AS2UC-C5RTO-T636O-CCBAP',
							success(re) {
								console.log("中文位置")
								console.log(re)
								if (re.statusCode === 200) {
									_this.submitInfo.customerDetailedAddress = re.data.result.address
									console.log("获取中文街道地理位置成功")
								} else {
									console.log("获取信息失败，请重试！")
								}
							}
						});
					}
				});
			},
			isGetLocation(a = "scope.userLocation") { // 3. 检查当前是否已经授权访问scope属性，参考下截图
				var _this = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting[a]) { //3.1 每次进入程序判断当前是否获得授权，如果没有就去获得授权，如果获得授权，就直接获取当前地理位置
							_this.getAuthorizeInfo()
						} else {
							_this.getLocationInfo()
						}
					}
				});
			},

			//################################################选择器部分############################################################
			handleTap(picker) {
				this.$refs[picker].show()
			},
			/**
			 * 设备型号监听回调
			 */
			handleChange(item) {
				console.log(item)
			},
			handleConfirm(item) {
				this.flags.typeNumberFlag = true
				this.submitInfo.equipmentTypeNumber = item.item.map(item => item.label).join(' ')
			},
			handleCancel(item) {},


			/**
			 * 设备配置监听回调
			 */
			handleChange2(item) {},
			handleConfirm2(item) {
				this.flags.configFlag = true
				this.submitInfo.configuration = item.item.map(item => item.label).join(' ')
			},
			handleCancel2(item) {},

			/**
			 * 墨水溶剂型号监听回调
			 */
			handleChange3(item) {},
			handleConfirm3(item) {
				this.flags.solventTypeFlag = true
				this.submitInfo.inkTankTypeNumber = item.item.map(item => item.label).join(' ')
			},
			handleCancel3(item) {},

			/**
			 * 售后负责人监听回调
			 */
			handleChange4(item) {},
			handleConfirm4(item) {
				this.flags.principalFlag = true
				this.submitInfo.maintainPeople = item.item.map(item => item.label).join(' ')
				this.submitInfo.maintainPeopleId = item.item.map(item => item.value).join(' ')
			},
			handleCancel4(item) {},

			/**
			 * 时间监听回调
			 */
			dateOnConfirm(eve) {
				this.flags.dateFlag = true
				this.submitInfo.installDate = eve.result
				console.log(eve)
			},
			//################################################验证部分############################################################
			/**
			 * 验证信息字段
			 */
			validate() {
				/**
				 * 定义验证规则
				 */
				let loginRules = [{
						name: 'equipmentTypeNumber',
						type: 'required',
						errmsg: '请选择设备型号！设备型号不能为空'
					},
					{
						name: 'configuration',
						type: 'required',
						errmsg: '请选择设备配置！设备配置不能为空'
					},
					{
						name: 'fuselageNumber',
						type: 'required',
						errmsg: '请输入设备机身号！机身号不能为空'
					},
					{
						name: 'inkTankTypeNumber',
						type: 'required',
						errmsg: '请选择墨水溶剂型号！溶剂型号不能为空'
					},
					{
						name: 'installDate',
						type: 'required',
						errmsg: '请选择安装日期！安装日期不能为空'
					},
					{
						name: 'maintainPeople',
						type: 'required',
						errmsg: '请选择负责人！负责人不能为空'
					},
					{
						name: 'subordinateCompany',
						type: 'required',
						errmsg: '请输入公司名称！公司名称不能为空'
					},
					{
						name: 'customerDetailedAddress',
						type: 'required',
						errmsg: '请输入用户详细地址！地址不能为空'
					},
					{
						name: 'customer',
						type: 'required',
						errmsg: '请输入客户联系人！联系人不能为空'
					},
					{
						name: 'customerContact',
						type: 'required',
						errmsg: '请填写客户联系方式！联系方式不能为空'
					},
				]
				let valLoginRes = validate.validate(this.submitInfo, loginRules)
				if (!valLoginRes.isOk) {
					uni.showToast({
						icon: 'none',
						title: valLoginRes.errmsg
					})
					return false
				}
				return true
			},
			//################################################录入工单部分############################################################
			/**
			 * 提交录入设备信息
			 */
			on() {
				/**
				 * 提交前先验证字段是否为空
				 */
				if (this.validate()) {
					this.submitInfo.imgUrl = this.basicArr[0]
					let that = this
					uni.showModal({
						title: '录入确认',
						content: '确定要录入设备吗？',
						success: function(res) {
							if (res.confirm) {
								console.log(that.submitInfo)
								creteEquipment(that.submitInfo).then((res) => {
									console.log(res)
									if (res.code == 1) {
										that.isSuccess = true
										uni.removeStorageSync("info")
										uni.reLaunch({
											url: '/pages/views/engineer/EnteringSuccess/EnteringSuccess?id=' + 2 + '&name=' + that.submitInfo.maintainPeople
										});
									} else {
										uni.showToast({
											icon: 'none',
											title: res.msg
										})
									}

								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});

				}

			},

			//################################################图片上传部分############################################################
			// 删除图片 -2019/05/12(本地图片进行删除)
			async delImgInfo(e) {
				console.log('你删除的图片地址为:', e, this.basicArr.splice(e.index, 1));
			},
			// 基础版
			async upBasicData(e) {
				console.log('===>', e);
				// 上传图片数组
				let arrImg = [];
				for (let i = 0, len = e.length; i < len; i++) {
					try {
						if (e[i].path_server != "") {
							await arrImg.push(e[i].path_server.split(','));
						}
					} catch (err) {
						console.log('上传失败...');
					}
				}
				// 图片信息保存到data数组
				this.basicArr = arrImg;
				// 可以根据长度来判断图片是否上传成功. 2019/4/11新增
				if (arrImg.length == this.upImgBasic.count) {
					uni.showToast({
						title: `上传成功`,
						icon: 'none'
					});
				}
			},
			/**
			 * 回显数据
			 */
			echo() {
				this.submitInfo = uni.getStorageSync("info") ? JSON.parse(uni.getStorageSync("info")) : this.submitInfo
				if (this.submitInfo.equipmentTypeNumber) {
					this.flags.typeNumberFlag = true
				}
				if (this.submitInfo.installDate) {
					this.flags.dateFlag = true
				}
				if (this.submitInfo.maintainPeople) {
					this.flags.principalFlag = true
				}
			}
		},
		/**
		 * 页面返回监听
		 */
		beforeDestroy(e) {
			console.log(e);
			if(!this.isSuccess){
				let _this = this
				uni.showModal({
					title: '退出提示',
					content: '检测到设备编辑未保存,是否保存',
					success: function(res) {
						if (res.confirm) {
							uni.setStorageSync("info", JSON.stringify(_this.submitInfo))
						} else if (res.cancel) {
							uni.removeStorageSync("info")
						}
						uni.navigateBack({
							delta: 1
						});
					}
				});
			}
		},
		onReady() {
			this.isGetLocation()

		},
		onShow() {
			/**
			 * 检验当前是否已经登录
			 */
			let curRoute = this.$mp.page.route;
			this.$intercept.permission(curRoute)
		},
		onLoad(op) {

			getEquipmentTypeList().then(res => {
				this.equipmentTypeNumbers = res.result
				console.log(res)
			})

			this.submitInfo.equipment_id = op.id;
			//######################################获取所有工程师######################################################
			/**
			 * 查询工程师信息
			 */
			getEngineerList().then((res) => {
					let engineers = res.result.data
					let arr2 = []
					engineers.forEach((cur, index, arr) => {
						arr2.push({
							value: arr[index].id,
							label: arr[index].name
						})
					})
					this.maintainPeoples = arr2
					this.showflag = true
					uni.hideLoading()
				}),

				//######################################获取所有设备型号######################################################

				// getEquipmentTypeList().then(res =>{
				// 	let equipmentType = res.result.data
				// 	let arr2 = []
				// 	equipmentType.forEach((cur,index,arr)=>{
				// 		arr2.push({value:arr[index].id,label:arr[index].type})
				// 	})
				// 	this.equipmentTypeNumbers = arr2
				// 	this.showflag = true
				// 	uni.hideLoading()
				// })

				/**
				 * 获取定位信息
				 */
				//######################################编辑草稿回显######################################################
				this.echo()
		}

	}
</script>

<style lang="scss">
	.select {
		color: #000000;
	}

	.container {
		width: 100%;
		background-color: #E6E6E6;
		height: 1658rpx;

		.one {
			height: 532rpx;
		}
		.one1 {
			height: 150rpx;
		}

		.two {
			height: 196rpx;
		}

		.three {
			height: 480rpx;
		}

		.four {
			height: 300rpx;

			.text {
				margin-top: 20rpx;
			}

			.add-img-box {
				width: 95%;
			}

		}

		.submit-button {
			width: 90%;
			background-color: #09BB07;
		}

		.item {
			height: 98rpx;
			width: 90%;
		}
		.textarea {
			margin-top: 20rpx;
			height: 150rpx;
			width: 90%;
		}
		
	}

	.text {
		width: 33.33%;
	}

	.input-content {
		height: 100%;
		width: 66.66%;
	}

	.picker {
		color: #8B8B8B;
	}

	.one,
	.one1,
	.two,
	.three,
	.four {
		background-color: #FFFFFF;
		width: 100%;
	}
</style>
